package com.crdeng.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crdeng.Utils.MD5Util;
import com.crdeng.handler.BusinessException;
import com.crdeng.response.ResultCode;
import com.crdeng.system.entity.Role;
import com.crdeng.system.entity.User;
import com.crdeng.system.mapper.RoleMapper;
import com.crdeng.system.mapper.UserMapper;
import com.crdeng.system.service.UserService;
import com.crdeng.system.vo.Permission;
import com.crdeng.system.vo.UserInfo;
import com.crdeng.system.vo.UserRoleVO;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author crdeng
 * @since 2020-11-16
 */
@Service

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

     @Autowired(required = false)
     private RoleMapper roleMapper;


    /**
     * 分页条件查询
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public IPage<User> findUserPage(IPage<User> page, Wrapper<User> queryWrapper) {
        return this.baseMapper.findUserPage(page, queryWrapper);
    }

    /**
     * 查询用户是否存
     * @param username
     * @return
     */
    @Override
    public UserRoleVO findByUsername(String username) {
        return this.baseMapper.findByUsername(username);
    }

    /**
     * 查询用户并且封装权限
     * @param username
     * @return
     */
    @Override
    public List<Permission> getGrantedAuthority(String username) {
        return this.baseMapper.getGrantedAuthority(username);
    }

    /**
     * 根据用户ID查询用户信息和部门名称
     * @param id
     * @return
     */
    @Override
    public UserInfo getUserById(Long id) {
        UserInfo userInfo = baseMapper.getUserById(id);
        List<String> roleName = roleMapper.getRoleNameByUserId(id);
        List<String> newRoleName=new ArrayList<>();
        for (String name : roleName) {
            newRoleName.add(name);
            newRoleName.add(" ");
        }
        userInfo.setRolename(newRoleName);
        return userInfo;
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void deleteUserById(Long id) {
        User user = baseMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(), ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        UserRoleVO userRoleVO = (UserRoleVO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断删除的用户是否是当前用户
        if (user.getId().equals(userRoleVO.getId())){
            throw  new  BusinessException(ResultCode.USER_ACCOUNT_NOT_NEW_DELETE.getCode(),ResultCode.USER_ACCOUNT_NOT_NEW_DELETE.getMessage());
        }
         baseMapper.deleteById(id);

    }

    /**
     * 编辑用户
     * @param user
     */
    @Override
    public void editUser(User user) {
        System.out.println(user.getId());
        User oldUser = baseMapper.selectById(user.getId());
        if (oldUser==null){
            throw  new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        if (!oldUser.getPassword().equals(user.getPassword())){
            user.setPassword(MD5Util.encode(user.getPassword()));
        }
        user.setModifiedTime(new Date());
        baseMapper.updateById(user);
    }

    /**
     * 查询用户已拥有的权限
     * @param id
     * @return
     */
    @Override
    public List<Integer> getROleList(Long id) {
        return roleMapper.getRoleListByUserId(id);
    }

    /**
     * 给用户分配角色
     * @param id  用户ID
     * @param roleId
     */
    @Override
    public void saveRoleByUserId(Long id, List<Integer> roleId) {
           /*判断用户是否存在*/
        User user = getById(id);
        if (user==null){
            throw  new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        if (roleId.size()!=0){
            List<Integer> allRoleId = roleMapper.getRoleId();
            /*判断传入的角色ID是否存在*/
            boolean flag = allRoleId.containsAll(roleId);
            if (!flag){
                throw  new BusinessException(ResultCode.ROLE_NOT_EXIST.getCode(),ResultCode.ROLE_NOT_EXIST.getMessage());
            }
        }
        //删除用户的所有角色
        roleMapper.deleteRole_User(id);
        //添加新的角色
        if (roleId.size()==0) {return;}
        for (Integer RId : roleId) {
            roleMapper.saveRole_User(id,RId);
        }
    }






}
